<template>
    <div class="login">
        <el-form :model="formValue" :rules="rules" label-width="120px" ref="form">
            <el-form-item label="手机号码"  prop="phone">
                <el-input v-model="formValue.phone"  />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="formValue.password" type="password"/>
            </el-form-item>
            <el-form-item :label-width="0">
                <el-button type="danger" style="width:300px" @click="login">登录</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive,defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../api/index'
import useStore from '../store/idnex.js'
import { def } from '@vue/shared';
const store = useStore()
const form = ref(null)

const emit = defineEmits(['getUserInfo'])

const formValue = reactive({
    phone: null,
    password: ''
})


const rules = reactive({
    phone: [
        { required: 'true', max:11, min:11, message: '请输入正确手机号', trigger: 'blur' }
    ],
    password: [
        { required: 'true', message: '密码不能为空', trigger: 'blur' }
    ]})



const login = () => {
    form.value.validate(async valid => {
        if (valid) {
              let res = await request("/login/cellphone",{
                phone:formValue.phone,
                password:formValue.password
              })
            //   登录成功 
              if (res.data.code == 200) {
                // 将请求到的用户id存入localStroage
                window.localStorage.setItem("userId",res.data.profile.userId)
                ElMessage.success("登陆成功！")
                // 通知父组件获取用户信息
                emit('getUserInfo',res.data.profile)
                // 修改store中的登陆状态
                store.updateLoginState(true)
                return
              }else if (res.data.code == 400) {
                ElMessage.error("手机号错误！")
                return
              }else if (res.data.code == 502) {
                ElMessage.error("密码错误！")
                return
              }else{
                ElMessage.error("登录失败，请稍后重试！")
              }
              formValue.password = ''
              formValue.phone = ''
            }
        })
}

</script>

<style lang="scss" scoped>
.login {
    width: 300px;
    height: 150px;
}
</style>